package com.github.binarywang.demo.wx.cp.controller;

import cn.hutool.core.lang.Pair;
import com.alibaba.fastjson.JSON;
import com.github.binarywang.demo.wx.cp.aes.*;
import com.github.binarywang.demo.wx.cp.constant.WxCpConstant;
import com.github.binarywang.demo.wx.cp.utils.CacheUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.json.XML;

import java.util.HashMap;
import java.util.Map;

/**
 * created by lanxinghua@2dfire.com on 2020/2/14
 */
public class ThirdBaseController {
    public static Map<String/*企业ID*/, String> map = new HashMap<>(10);
    {
        map.put("ww4007bc86bede5885", "TZHy4W3MVVI4iEnfYfZqp2bYxK-vjNtDKFz5AIsG8g0");
    }

    public static String sCorpID = "ww4007bc86bede5885";

    // 第三方应用
    public static String suiteID = "ww141f5c1b0bfe0bc2";

    public static String sToken = "ECeyv";
    public static String sEncodingAESKey = "kYkZ8YiM7Xze6HbyHTzmmOs1XqvH8Ps4MhxOdaBWqG4";
    public static String suiteSecret = "NpR7i2nC_lAdr-nhm4ChYEGAnHpzQK128F2YKtMzDXc";

    public static WXBizMsgCrypt wxcpt = null;

    static {
        try {
            wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        } catch (AesException e) {
            e.printStackTrace();
        }
    }

    public static final Double twoHours = 1000*60*60*1.5;// 1.5个小时


    /**
     * 获取操作方式type
     * @param decryptMsgs
     * @return
     */
    public static Pair<String, JSONObject> doType(String decryptMsgs){
        try {
            org.json.JSONObject jsonObject = XML.toJSONObject(decryptMsgs.replace("<xml>", "").replace("</xml>", ""));
            String infoType = jsonObject.getString(WxCpConstant.INFO_TYPE);
            if (StringUtils.isBlank(infoType)){
                throw new Exception("infoType为空");
            }
            return new Pair<String, org.json.JSONObject>(infoType, jsonObject);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 从缓存中获取suiteAccessToken
     * @return
     */
    public static String getSuiteAccessToken() throws WxErrorException {
        String value = CacheUtil.get(CacheUtil.suiteAccessToken_key);
        if (StringUtils.isEmpty(value)) {
            return value;
        }
        String[] values = value.split(":");
        if (values.length < 2){
            return null;
        }
        Long startTime = Long.valueOf(values[0]);
        Long endTime = System.currentTimeMillis();
        if ((endTime - startTime) < twoHours.longValue()){
            return value.split(":")[1];
        }
        // 过期
        return null;
    }


    /**
     * 返回明文
     * @param msg_signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    public static String verifyUrl(String msg_signature, String timestamp, String nonce, String echostr) {
        try {
            System.err.println(msg_signature + "-|-" + timestamp + "-|-" + nonce + "-|-" + echostr);
            String s = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);
            return s;
        } catch (AesException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取第三方应用凭证suite_access_token 有效期2h
     * @param jsonObject
     */
    public static SuiteR getSuiteToken(org.json.JSONObject jsonObject) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token";
        Suite suite = new Suite();
        suite.setSuite_id(jsonObject.get(WxCpConstant.SUITE_ID).toString());
        suite.setSuite_secret(suiteSecret);
        suite.setSuite_ticket(jsonObject.get(WxCpConstant.SUITE_TICKET).toString());
        com.alibaba.fastjson.JSONObject re = HttpUt.sendPost(url, JSON.toJSONString(suite));
        SuiteR suiteR = JSON.toJavaObject(re, SuiteR.class);
        System.out.println("获取第三方应用凭证suite_access_token:" + suiteR.toString());
        CacheUtil.put(CacheUtil.suiteAccessToken_key, System.currentTimeMillis() + ":" + suiteR.getSuite_access_token());
        return suiteR;
    }


    /**
     * 获取预授权码
     * @param suiteAccessToken
     * @return
     */
    public static String getPreAuthToken(String suiteAccessToken) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=";
        url = url + suiteAccessToken;
        com.alibaba.fastjson.JSONObject re = HttpUt.sendGet(url);
        System.out.println("预授权码："+re.toJSONString());
        return re.getString("pre_auth_code");
    }


    /**
     * 获取永久授权码
     * @param suiteAccessToken
     * @param auth_code  临时授权码
     * @return
     */
    public static String getPermanentCode(String suiteAccessToken, String auth_code) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token=";
        url = url + suiteAccessToken;
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("auth_code", auth_code);
        com.alibaba.fastjson.JSONObject re = HttpUt.sendPost(url, object.toJSONString());
        System.out.println("获取永久授权信息："+re.toJSONString());
        return re.getString("permanent_code");
    }



    /**
     * 获取企业授权信息   accessToken 获取之后，就跟普通企业一样使用token调用API接口
     * @param suiteAccessToken
     * @param auth_corpId
     * @param permanent_code
     * @return
     */
    public static com.alibaba.fastjson.JSONObject getAuthInfo(String suiteAccessToken, String auth_corpId, String permanent_code){
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=";
        url = url + suiteAccessToken;
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("auth_corpid", auth_corpId);
        object.put("permanent_code", permanent_code);
        com.alibaba.fastjson.JSONObject re = HttpUt.sendPost(url, object.toJSONString());
        System.out.println("企业授权信息："+re.toJSONString());
        System.out.println(re.getString("access_token"));
        return re;
    }


    /**
     * 获取openId
     * @param userId
     * @return
     * @throws Exception
     * {"errcode":0,"openid":"o6og66O7WUdYSbjeFNGRSmvYAbfk","errmsg":"ok"}
     */
    public static String getOpenId(String accessToken, String userId) throws Exception {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=%s";
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("userid", userId);
        com.alibaba.fastjson.JSONObject result = HttpUt.sendPost(String.format(url, accessToken), object.toJSONString());
        System.out.println(result.toJSONString());
        return result.getString("openid");
    }


    /**
     * 获取企业用户信息
     * @param access_token
     * @param userId
     * @throws Exception
     */
    public static void getCoperInfo(String access_token, String userId) throws Exception{
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s";
        com.alibaba.fastjson.JSONObject result = HttpUt.sendGet(String.format(url, access_token, userId));
        System.out.println("企业用户详细："+result.toJSONString());
    }



    /**
     * 发送欢迎语
     * @param access_token
     * @param welcome_code
     * @throws Exception
     */
    public static void sendWelcome(String access_token, String welcome_code) throws Exception{
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg?access_token=%s";
        String postData = "{\n" +
            "    \"welcome_code\":\""+ welcome_code +"\",\n" +
            "    \"text\": {\n" +
            "        \"content\":\"文本消息内容\"\n" +
            "    },\n" +
            "    \"link\": {\n" +
            "        \"title\": \"消息标题\",\n" +
            "        \"picurl\": \"https://example.pic.com/path\",\n" +
            "        \"desc\": \"消息描述\",\n" +
            "        \"url\": \"https://example.link.com/path\"\n" +
            "    },\n" +
            "}\n";
        com.alibaba.fastjson.JSONObject result = HttpUt.sendPost(String.format(url, access_token), postData);
        System.out.println("企业用户详细："+result.toJSONString());
    }


    /**
     * 获取企业应用的accessToken
     * @throws Exception
     */
    public static String getAccessToken(boolean isTwoFire) throws Exception{
        String auth_corpId = "wwd276de90ff82e1e3";
        String permCode = "D-4Lz9BX9oYuUkwvVw_oST2Xs1PvG7u6mes6fPvf4lM";
        if (isTwoFire){
            auth_corpId = "ww4007bc86bede5885";
            permCode = "TZHy4W3MVVI4iEnfYfZqp2bYxK-vjNtDKFz5AIsG8g0";
        }
        // 第三方获取到企业应用的accessToken，就和普通模式一样调用接口了
        String accessToken = getAuthInfo(getSuiteAccessToken(), auth_corpId, permCode).getString("access_token");
        System.out.println("getAccessToken:" + accessToken);
        return accessToken;
    }

}
